<template>
  <div class="reigist">
    <button
      class="avatar-wrapper"
      open-type="chooseAvatar"
      @chooseavatar="onChooseAvatar"
    >
      <image class="avatar" :src="avatarUrl"></image>
    </button>
    <div class="inp" style="display: flex; align-items: center">
      <span>昵称：</span>
      <input
        v-model="nickName"
        type="nickname"
        class="weui-input"
        placeholder="请输入昵称"
      />
    </div>
    <div style="padding: 40rpx">
      <uv-button
        @click="save"
        customTextStyle="font-size:24rpx"
        type="error"
        shape="circle"
        :hairline="true"
        text="保存"
      ></uv-button>
    </div>
  </div>
</template>

<script setup>
import { onShow } from "@dcloudio/uni-app";
import { ref } from "vue";
import { setUserInfo } from "../https/api/reigist";
onShow(() => {
  avatarUrl.value = JSON.parse(uni.getStorageSync("userInfo")).pic;
  nickName.value = JSON.parse(uni.getStorageSync("userInfo")).nickName;
});
let avatarUrl = ref("");
let nickName = ref("");
let onChooseAvatar = (e) => {
  avatarUrl.value = e.detail.avatarUrl;
};

let save = async () => {
  uni.getFileSystemManager().readFile({
    filePath: `${avatarUrl.value}`, //选择图片返回的相对路径
    encoding: "base64", //编码格式
    success: async (res) => {
      let obj = {
        nickName: nickName.value,

        avatarUrl: `data:image/png;base64,${res.data}`,
      };

      await setUserInfo(obj);

      uni.showToast({
        title: "保存成功",
        icon: "none",
      });
      uni.switchTab({
        url: "/pages/my",
      });
    },
    fail: async() => {
      let obj = {
        nickName: nickName.value,

        avatarUrl:avatarUrl.value ,
      };
      await setUserInfo(obj);
      uni.showToast({
        title: "保存成功",
        icon: "none",
      });
      uni.switchTab({
        url: "/pages/my",
      });
    },
  });
};
</script>

<style lang="scss" scoped>
.inp {
  border: 1px solid transparent;
  padding: 20rpx 30rpx;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
}
.reigist {
  box-sizing: border-box;
}

.avatar-wrapper {
  padding: 0;
  width: 56px !important;
  border-radius: 8px;
  margin-top: 40px;
  margin-bottom: 40px;
}

.avatar {
  display: block;
  width: 56px;
  height: 56px;
}

.container {
  display: flex;
}
</style>
